<template>
  <div>
    <!--
    action:
   如果向自己服务器发送请求上传图片：需要有url请求地址
   如果向腾讯cos服务器发送请求：#[不需要写地址]
     -->

    ==={{ value }}
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress type="line" :percentage="percentage" class="progress" />
    </el-upload>
  </div>
</template>

<script>
/* 实现腾讯云上传步骤 */

/* 1-下载包和获取秘钥 */
var COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDZ12rPhjX5PUQ6YnOuABvQimfPuAD1jLh',
  SecretKey: '7yZv3wZuQkpgSCnDQP9et363oNjslNtM'
})
export default {
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      imageUrl: '',
      percentage: 0,
      showProgress: false
    }
  },
  watch: {
    value(newVal) {
      console.log(newVal, 55)
      this.imageUrl = newVal
    }
  },

  created() {
    console.log(this.value, 7777)
  },
  methods: {
    upload({ file }) {
      this.showProgress = true
      /* 实现将图片上传到腾讯云cos中 */
      console.log(file, 111111)
      /* 2-调用腾讯云sdk中的api方法实现将图片上传到腾讯云 */
      cos.uploadFile(
        {
          Bucket:
            'web87-1253551029' /* 填写自己的bucket，必须字段   存储桶的名称 */,
          Region: 'ap-chongqing' /* 存储桶所在地域，必须字段 */,
          Key: file.name /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
          Body: file, // 上传文件对象
          SliceSize:
            1024 *
            1024 *
            5 /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */,
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData), 66666)
            this.percentage = (progressData.loaded / progressData.total) * 100
            this.showProgress = false
          }
        },
        (err, data) => {
          if (err) {
            console.log('上传失败', err)
          } else {
            // console.log(this, 222333)
            this.imageUrl = 'https://' + data.Location
          }
        }
      )
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>